*test version includes a measure on exporting side for share of dollar for competitors

clear
set more 1
set type double

capture log using "log/competitor_currency.log", replace
*****************************************************************
*NOTES:
*construct a measure of competitors average size and average phi within HS4-destination
*uses 2017 to 2019 weights
*******************************************************************************************

use ../../rawdata/X_2019, clear
	append using ../../rawdata/X_2018
	append using ../../rawdata/X_2017
	rename land cty_code
	drop if cty_code=="EU"	
	drop if flow=="XI"
	destring cncode, replace
	gen hs4=int(cncode/10000)

collapse (mean) value, by(vat hs4 cty_code)
preserve
	merge m:1 vat using ../data/mphi_xeu_currency, keep(match) nogen
	
*mphi_xeu	
	drop if missing(mphi_xeu)
	gen value_mphi_xeu=value*mphi_xeu
	egen totvalue_mphi_xeu=sum(value_mphi_xeu), by(cty_code hs4)
	egen totvalue=sum(value), by(cty_code hs4)
	gen comp_mphi_xeu=(totvalue_mphi_xeu - value_mphi_xeu)/(totvalue - value)
	
*mphi_xeu_other
	gen value_mphi_xeu_other=value*mphi_xeu_other
	egen totvalue_mphi_xeu_other=sum(value_mphi_xeu_other), by(cty_code hs4)
	gen comp_mphi_xeu_other=(totvalue_mphi_xeu_other - value_mphi_xeu_other)/(totvalue - value)

*mphi_xeu_dollar
	gen value_mphi_xeu_dollar=value*mphi_xeu_other
	egen totvalue_mphi_xeu_dollar=sum(value_mphi_xeu_dollar), by(cty_code hs4)
	gen comp_mphi_xeu_dollar=(totvalue_mphi_xeu_dollar - value_mphi_xeu_dollar)/(totvalue - value)
	
	keep vat cty_code hs4 comp_mphi_xeu*
	save temp/comp_mphi_xeu, replace
restore
	merge m:1 vat using ../data/memp, keep(match) nogen
	drop if missing(memp)
	
	gen value_memp=value*memp
	egen totvalue_memp=sum(value_memp), by(cty_code hs4)
	egen totvalue=sum(value), by(cty_code hs4)
		
	gen comp_memp=(totvalue_memp - value_memp)/(totvalue - value)
	drop if missing(comp_memp)
	keep vat cty_code hs4 comp_memp
	save temp/comp_memp, replace
	
	merge 1:1 vat cty_code hs4 using temp/comp_mphi_xeu, nogen
	
save ../data/comp_instruments, replace
	



log close